package com.bsoft.gol.hbs.dao;

import com.bsoft.gol.hbs.bean.Vo.HealthInfoReplyBaseVO;
import com.bsoft.gol.hbs.bean.qo.HealthInfoReplyListQo;
import com.bsoft.gol.hbs.bean.qo.NewReplyListQo;
import ctd.persistence.annotation.DAOMethod;
import ctd.persistence.annotation.DAOParam;
import ctd.persistence.support.hibernate.template.AbstractHibernateStatelessResultAction;
import ctd.persistence.support.hibernate.template.HibernateSessionTemplate;
import ctd.persistence.support.hibernate.template.HibernateStatelessResultAction;
import hcn.base.healthinfo.HealthInfoReply;
import hcn.base.healthinfo.vo.NewReplyListVO;
import org.atag.dao.action.QoHibernateStatelessResultAction;
import org.atag.dao.ext.HibernateExtendDAO;
import org.atag.dao.model.SimplePageInfo;
import org.hibernate.Query;
import org.hibernate.StatelessSession;
import pcn.bean.FindPatientLeaveMessageVo;
import pcn.bean.consultation.FindPatientLeaveMessageQo;

import java.util.List;

/**
 * 健康资讯评论回复数据库访问层
 *
 * @author linyi
 * @date 2021/10/9 16:36
 */
public abstract class HealthInfoReplyDAO extends HibernateExtendDAO<HealthInfoReply> {


    /**
     * 根据文章主键查询出所有相关的评论列表
     *
     * @param articleId 文章主键
     */
    @DAOMethod(sql = "from HealthInfoReply where articleId=:articleId")
    public abstract List<HealthInfoReply> getByArticleId(@DAOParam("articleId") Long articleId);

    /**
     * 根据参数查询出文章相关的评论列表 带分页
     */
    public SimplePageInfo<HealthInfoReplyBaseVO> getPageByParam(HealthInfoReplyListQo qo) {
        QoHibernateStatelessResultAction<HealthInfoReplyBaseVO, HealthInfoReplyListQo> action = getReplyListActionByParam(qo, true);
        HibernateSessionTemplate.instance().execute(action);
        return action.getSimpleResultPage();
    }

    /**
     * 根据参数查询出文章相关的评论列表 不分页
     */
    public List<HealthInfoReplyBaseVO> getListByParam(HealthInfoReplyListQo qo) {
        QoHibernateStatelessResultAction<HealthInfoReplyBaseVO, HealthInfoReplyListQo> action = getReplyListActionByParam(qo, false);
        HibernateSessionTemplate.instance().execute(action);
        return action.getResultList();
    }

    /**
     * 插入
     * INSERT INTO health_info_reply
     * (p_reply_id,target_reply_id,reply_time,reply_content,reply_user_role,reply_user_id,reply_user_name,
     * target_user_id,target_user_name,target_user_role,gmt_create,gmt_modified)
     * VALUES
     * (xx)
     */
    public void insert(HealthInfoReply insert) {
        HibernateStatelessResultAction<Void> action = new AbstractHibernateStatelessResultAction<Void>() {
            @Override
            public void execute(StatelessSession statelessSession) {
                String builder = " INSERT INTO health_info_reply" +
                        " (article_id,p_reply_id,target_reply_id,reply_time,reply_content,reply_user_role,reply_user_id,reply_user_name," +
                        " target_user_id,target_user_name,target_user_role,gmt_create,gmt_modified)" +
                        " VALUES" +
                        " (:articleId,:pReplyId,:targetReplyId,:replyTime,:replyContent,:replyUserRole,:replyUserId,:replyUserName," +
                        " :targetUserId,:targetUserName,:targetUserRole,:gmtCreate,:gmtModified)";
                Query query = statelessSession.createSQLQuery(builder);
                query.setParameter("articleId", insert.getArticleId());
                query.setParameter("pReplyId", insert.getpReplyId());
                query.setParameter("targetReplyId", insert.getTargetReplyId());
                query.setParameter("replyTime", insert.getReplyTime());
                query.setParameter("replyContent", insert.getReplyContent());
                query.setParameter("replyUserRole", insert.getReplyUserRole());
                query.setParameter("replyUserId", insert.getReplyUserId());
                query.setParameter("replyUserName", insert.getReplyUserName());
                query.setParameter("targetUserId", insert.getTargetUserId());
                query.setParameter("targetUserName", insert.getTargetUserName());
                query.setParameter("targetUserRole", insert.getTargetUserName());
                query.setParameter("gmtCreate", insert.getGmtCreate());
                query.setParameter("gmtModified", insert.getGmtModified());
                query.executeUpdate();
            }
        };
        HibernateSessionTemplate.instance().execute(action);
    }

    /**
     * 公用查询
     * SELECT
     * reply_id AS replyId,
     * article_id AS articleId,
     * p_reply_id AS pReplyId,
     * target_reply_id AS targetReplyId,
     * reply_time AS replyTime,
     * reply_content AS replyContent,
     * reply_user_id AS replyUserId,
     * reply_user_name AS replyUserName,
     * target_user_id AS targetUserId,
     * target_user_name AS targetUserName
     * FROM
     * health_info_reply
     *
     * @param qo     查询参数
     * @param isPage 是否需要分页
     * @author linyi
     * @date 2021/10/11 13:12
     */
    private QoHibernateStatelessResultAction<HealthInfoReplyBaseVO, HealthInfoReplyListQo> getReplyListActionByParam(HealthInfoReplyListQo qo, boolean isPage) {
        QoHibernateStatelessResultAction<HealthInfoReplyBaseVO, HealthInfoReplyListQo> action
                = new QoHibernateStatelessResultAction<>(isPage, qo, HealthInfoReplyBaseVO.class);
        String builder = " SELECT {{" +
                " reply_id AS replyId," +
                " is_read AS isRead," +
                " article_id AS articleId," +
                " p_reply_id AS pReplyId," +
                " target_reply_id AS targetReplyId," +
                " reply_time AS replyTime," +
                " reply_content AS replyContent," +
                " reply_user_id AS replyUserId," +
                " reply_user_name AS replyUserName," +
                " target_user_id AS targetReplyUserId," +
                " target_user_name AS targetReplyUserName }}" +
                " FROM health_info_reply" +
                " WHERE 1=1";
        action.setSql(builder);
        //添加条件语句
        action.addCondition(" AND article_id=:articleId");
        //一级留言
        if (qo.isFirst()) {
            action.addSql(" AND target_reply_id IS NULL");
        }
        //二级留言
        if (qo.isSecond()) {
            action.addSql(" AND target_reply_id IS NOT NULL");
        }
        //排除自己
        if (qo.isExcludeSelf()) {
            action.addCondition(" AND reply_user_id <> :replyUserId");
        }
        //只看自己
        if (qo.isOnlySelf()) {
            action.addCondition(" AND reply_user_id = :replyUserId");
        }
        if (qo.isDesc()) {
            action.addOrder(" ORDER BY reply_time DESC");
        } else {
            action.addOrder(" ORDER BY reply_time ASC");
        }

        return action;
    }

    /**
     * @param qo
     * @param isPage
     * @return org.atag.dao.model.SimplePageInfo<pcn.bean.FindPatientLeaveMessageVo>
     * @description: 查询未读患者留言列表
     * @author: zsf
     * @date: 2023/8/2 0002 17:05
     */
    public SimplePageInfo<FindPatientLeaveMessageVo> getReplyListActionByParam(FindPatientLeaveMessageQo qo, boolean isPage) {
        QoHibernateStatelessResultAction<FindPatientLeaveMessageVo, FindPatientLeaveMessageQo> action
                = new QoHibernateStatelessResultAction<>(isPage, qo, FindPatientLeaveMessageVo.class);
        String builder = " SELECT {{" +
                " a.reply_id AS replyId," +
                " a.article_id AS articleId," +
                " a.reply_user_name AS replyUserName," +
                " b.title AS title }}" +
                " FROM health_info_reply a LEFT JOIN health_info b on a.article_id = b.article_id  " +
                " WHERE  a.is_read = 0 ";
        action.setSql(builder);
        //添加条件语句
        action.addCondition(" AND b.author_id= :replyUserId and b.article_status = '3' ");
        action.addCondition(" AND (a.target_user_id = :replyUserId or a.target_user_id is null)");
        action.addOrder(" ORDER BY a.gmt_create DESC ");
        HibernateSessionTemplate.instance().execute(action);
        return action.getSimpleResultPage();
    }


    /**
     * 获取回复医生的文章列表信息
     * SELECT
     * A.article_id AS articleId,
     * A.reply_user_name AS replyUserName,
     * A.reply_time AS replyTime
     * FROM
     * health_info B
     * INNER JOIN (
     * SELECT
     * article_id,
     * reply_user_name,
     * reply_time
     * FROM
     * health_info_reply
     * WHERE
     * is_read = 0
     * AND p_reply_id IS NULL UNION ALL
     * SELECT
     * article_id,
     * reply_user_name,
     * reply_time
     * FROM
     * health_info_reply
     * WHERE
     * is_read = 0
     * AND target_user_id = 'c536d96e6011455f8dfe518990b3c52e'
     * ) AS A ON B.article_id = A.article_id
     * AND B.author_id = 'c536d96e6011455f8dfe518990b3c52e' AND B.article_status = '3'
     * ORDER BY
     * replyTime DESC
     */
    public SimplePageInfo<NewReplyListVO> getNewReplyList(NewReplyListQo qo) {

        QoHibernateStatelessResultAction<NewReplyListVO, NewReplyListQo> action
                = new QoHibernateStatelessResultAction<>(true, qo, NewReplyListVO.class);
        String sql = "SELECT" +
                " {{A.article_id AS articleId," +
                " A.reply_user_name AS replyUserName," +
                " A.reply_id as replyId, " +
                " A.reply_user_name as patientName, " +
                " A.reply_content as content, " +
                " A.is_read as readFlag, " +
                " B.title, " +
                " A.reply_time AS replyTime}} " +
                " FROM health_info_reply A LEFT JOIN health_info B on a.article_id = b.article_id " +
                " WHERE (is_read = 0 or DATE_FORMAT(gmt_read, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d')) " +
                " AND b.author_id=:userId and b.article_status = '3' " +
                " AND (a.target_user_id = :userId  or a.target_user_id is null) " +
                " ORDER BY a.gmt_create DESC ";
        action.setSql(sql);
        action.addParamValue("userId", qo.getUserId());
        HibernateSessionTemplate.instance().execute(action);
        return action.getSimpleResultPage();
    }


    /**
     * 根据articleId 查询是否有未读的留言
     * SELECT DISTINCT
     * ( article_id )
     * FROM
     * health_info_reply
     * WHERE
     * is_read =0
     * AND article_id IN (xxx)
     */
    @DAOMethod(sql = "SELECT DISTINCT ( articleId ) from HealthInfoReply WHERE isRead = 0 AND articleId IN (:articleIds)")
    public abstract List<String> findNewReply(@DAOParam("articleIds") List<String> articleIds);

    /**
     * @param replyId
     * @return void
     * @description: 更新留言状态
     * @author: zsf
     * @date: 2023/8/2 0002 17:46
     */
    @DAOMethod(sql = "update HealthInfoReply set isRead=1 where  replyId =:replyId")
    public abstract void updatePatientLeaveMessage(@DAOParam("replyId") Long replyId);

    /**
     * 单条件更新字段值 update${目标字段}By${条件字段}
     * 相当于 update A set na =:na where cd =:cd;
     */
    @DAOMethod
    public abstract void updateIsReadByArticleId(Boolean isRead, String articleId);

    @DAOMethod(sql = "select count(1) from HealthInfo where doctorId in:doctorIds and articleStatus=3 ")
    public abstract long getCountByDoctorIds(@DAOParam("doctorIds") List<String> doctorIds);
}
